/*************************************************************************
 *  Copyright © 2023-2030 FXB CO.,LTD. All rights reserved.
 *------------------------------------------------------------------------
 *  公司：DefaultCompany
 *  项目：CustomBuildProcess
 *  文件：BuildLogUpgrade.cs
 *  作者：Administrator
 *  日期：2025/6/19 20:24:28
 *  功能：Nothing
*************************************************************************/

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace CustomBuildProcess.Editor
{
    /// <summary>
    /// 旧版升级
    /// </summary>
    public class BuildLogUpgrade
    {
        /// <summary>
        /// 升级，把日志全部重新往里写一遍
        /// </summary>
        [MenuItem("Edit/Build Log/Upgrade")]
        public static async Task UpgradeAsync()
        {
            string htmlLogPath = PathManager.BuildLogHtmlPath;
            string htmlLogTemplatePath = PathManager.BuildLogHtmlEncryptTemplatePath;
            string LogItemTemplatePath = PathManager.LogItemHtmlTemplatePath;

            try
            {
                string htmlContent = LogInfoHtmlOutput.BuildEncryptHtmlHeader(htmlLogTemplatePath);

                //获取到所有的日志信息，循环写入
                BuildConfigItem logConfigItem = Resources.Load<BuildConfigItem>(PathManager.BuildConfigItemPath);
                BuildInfoConfig configAsset = AssetDatabase.LoadAssetAtPath<BuildInfoConfig>(PathManager.BuildConfigPath);

                string newLogBlock = "";

                for (int i = configAsset.buildInfos.Count - 1; i >= 0; i--)
                {
                    BuildInfo info = configAsset.buildInfos[i];
                    newLogBlock += "\n" + LogInfoHtmlOutput.BuildLogHtml(LogItemTemplatePath, info, logConfigItem);
                }

                int scriptStart = htmlContent.IndexOf("<script id=\"encryptedData\"", StringComparison.Ordinal);
                if (scriptStart >= 0)
                {
                    int contentStart = htmlContent.IndexOf('>', scriptStart) + 1;
                    int contentEnd = htmlContent.IndexOf("</script>", contentStart);

                    // 重新加密
                    string encryptedNew = AesEncryptor.Encrypt(newLogBlock);

                    // 替换 HTML 中的加密内容
                    htmlContent = htmlContent.Substring(0, contentStart) + encryptedNew + htmlContent.Substring(contentEnd);
                }

                // 写入文件
                using (StreamWriter writer = new StreamWriter(htmlLogPath, false, Encoding.UTF8))
                {
                    await writer.WriteAsync(htmlContent);
                }

                Debug.Log($"Build log upgrade successful");

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogError($"Build log upgrade failed {e.Message}");
            }
        }


        public static bool IsNeedUpgrade()
        {
            string htmlLogPath = PathManager.BuildLogHtmlPath;

            if (!File.Exists(htmlLogPath))
            {
                return false;
            }

            string htmlContent = File.ReadAllText(htmlLogPath);

            string newLogTag = "<script id=\"encryptedData\" type=\"application/json\">";
            if (htmlContent.Contains(newLogTag))
            {
                return false;
            }

            return true;
        }
    }
}


